package com.gpscookie.vocabularystory;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

public class PlayScreen extends AbstractActivity {
    private int filter;
	private boolean isHide;
	private int currentPos;
	private Entry item;
	private long sleep = 2000;
	private TextView txtEntry;
	private TextView txtShortDesc;	
	private TextView txtProgress;
	private boolean pausing = false;
	private int totalWords;
	private boolean isReading = true;
	private TextView txtPause;

	@Override
	public void onResume() {
		super.onResume();
        if (Utils.INSTANCE.tts != null) {
        	Utils.INSTANCE.tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener(){
				public void onUtteranceCompleted(String utteranceId) {
					if (!pausing) {
						if ("entryend".equalsIgnoreCase(utteranceId)) {
							new EntryListDownloadTask().execute(currentPos);
						}
					}
				}        		
        	});
        }		
	}
	
	@Override
	public void onPause() {
		super.onPause();
		pausing = true;
		if (Utils.INSTANCE.tts != null) {
			Utils.INSTANCE.tts.stop();
			Utils.INSTANCE.tts.setOnUtteranceCompletedListener(null);
		}
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play);
        
        ToggleButton btnMute = (ToggleButton)findViewById(R.id.btnmute);
        btnMute.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				isReading = !isChecked;
//				if (!isReading) {
//					if (Utils.INSTANCE.tts!=null) {
//						Utils.INSTANCE.tts.stop();
//					}
//				}
			}        	
        });
        
        txtPause = (TextView)findViewById(R.id.txtpause);
        txtEntry = (TextView)findViewById(R.id.txtentry);
        txtShortDesc = (TextView)findViewById(R.id.txtshortdesc);
        txtProgress = (TextView)findViewById(R.id.txtprogress);
        txtEntry.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				pausing = !pausing;
				if (pausing) {
					txtPause.setText(getString(R.string.paused));
				} else {
					txtPause.setText(getString(R.string.playing));
					new EntryListDownloadTask().execute(currentPos);
				}
				Log.i("PlayScreen:onClick():", "pause "+pausing);		
			}        	
        });
        
        Intent it = this.getIntent();
        filter = it.getIntExtra("filter", 0);
        isHide = it.getBooleanExtra("hide", false);
        currentPos = (it.getIntExtra("current", 1)-1)*Utils.INSTANCE.pageSize;
        SimpleDBHelper db = new SimpleDBHelper(this);        
        totalWords = db.countEntryList(Utils.INSTANCE.currentBook.getKey(), filter); 
        db.close();
        
        item = null;
        new EntryListDownloadTask().execute(currentPos);
    }
	
	private class EntryListDownloadTask extends AsyncTask<Integer, Void, Void> {
		
		@Override
		protected Void doInBackground(Integer... params) {
			int current = params[0];
			Log.i("PlayScreen:EntryListDownloadTask:doInBackground():", "currentPos "+current);			
			if (Utils.INSTANCE.currentBook==null) {
				item = null;
			} else {
				SimpleDBHelper db = new SimpleDBHelper(PlayScreen.this);
				Book book = Utils.INSTANCE.currentBook;
				item = db.queryEntry(book.getKey(), filter, current);
				db.close();
			}
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void v) {
			if (!pausing) {
				txtPause.setText(getString(R.string.playing));
				if (item != null) {
					txtEntry.setText(item.getEntry());
					if (!isHide) {
						txtShortDesc.setText(item.getShortdesc());
					}
					currentPos++;
					txtProgress.setText(String.format("%d/%d", currentPos, totalWords));
					
					// read and spell it
					if (isReading && Utils.INSTANCE.tts!=null) {
						Utils.INSTANCE.tts.speak(item.getEntry(), TextToSpeech.QUEUE_FLUSH, null);
						for (int i=0; i<item.getEntry().length(); i++) {
							Utils.INSTANCE.tts.speak(item.getEntry().substring(i, i+1), TextToSpeech.QUEUE_ADD, null);
						}
						Utils.INSTANCE.tts.speak("spells", TextToSpeech.QUEUE_ADD, null);
						HashMap<String, String> end = new HashMap<String, String>();
						end.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "entryend");
						Utils.INSTANCE.tts.speak(item.getEntry(), TextToSpeech.QUEUE_ADD, 
								end);
					} else {
						new EntryListDownloadTask().execute(currentPos);
					}
				}
			} else {
				txtPause.setText(getString(R.string.paused));
			}
		}		
	}
}
